package org.xx.armory.rpc.decorators;

import org.xx.armory.db.SessionFactories;
import org.xx.armory.db.SessionFactory;
import org.xx.armory.db.TransactionManager;
import org.xx.armory.rpc.Decorator;
import org.xx.armory.security.AuthenticationToken;
import org.xx.armory.service.security.impl.OracleUserPermProvider;

import static org.xx.armory.commons.Validators.notEmpty;
import static org.xx.armory.commons.Validators.notNull;

public class OracleAuthorizationDecorator
        extends AbstractDbContextAuthorizationDecorator
        implements Decorator {
    /**
     * {@inheritDoc}
     */
    @Override
    protected boolean isPermitted(
            AuthenticationToken token,
            int[] permissions,
            TransactionManager transactionManager
    )
            throws Exception {
        notNull(token, "token");
        notEmpty(permissions, "permissions");
        notNull(transactionManager, "transactionManager");

        try (final SessionFactory sessionFactory = SessionFactories.createFactory("oracle")) {
            sessionFactory.setTransactionManager(transactionManager);
            sessionFactory.initialize();

            final OracleUserPermProvider userPermProvider = new OracleUserPermProvider();
            userPermProvider.setSessionFactory(sessionFactory);
            return userPermProvider.isPermitted(token.getUserId(), permissions);
        }
    }
}
